# -*- coding:utf-8 -*-
__author__ = 'root'
import os
import pandas as pd
from common_module.path_handle import reception_base_path



class word_dcit:
    def __init__(self):
        self.__word_dict_pd_name=os.path.join(reception_base_path,'word_dict.csv')

    def filter_words(self,*args):
        '''
        对词汇根据固化的词汇表进行过滤，过滤出存在的词汇
        :param args:
        :return:
        '''
        items={}
        items['code']=1  #0为成功 1为失败
        items['msg']=u''
        items['data']={}
        if args.__len__()<1:
            items['msg']=u'待过滤词汇为空'
            return items
        word_dataframe=pd.read_csv(self.__word_dict_pd_name,encoding='utf-8')
        filter_words=word_dataframe[word_dataframe['word'].isin(args)]   #过滤出来的词汇 dataframe
        word_index=filter_words.index.values
        word_value=filter_words.word.values
        if word_index.__len__()<1:
            items['code']=0
            items['msg']=u'过滤分词成功，但无分词'
            return items
        temp={}
        for i in range(word_index.__len__()):
            temp[word_index[i]]=word_value[i]
        items['data']=temp
        items['code']=0
        items['msg']=u'分词成功'
        return items



class material_handle:
    def __init__(self):
        self.__proportion_file_path=os.path.join(reception_base_path,'word_word_proportion.csv')   #分词与分词之间的比重关系
        self.__columns=['word_id','proportion_1','proportion_2','proportion_3','proportion_4','proportion_5','proportion_6']   #分词与分词之间的比重关系的字段名字
        self.__word_material_proportion_file_path=os.path.join(reception_base_path,'word_material_proportion.csv')   #词库与素材权重映射
        self.__proportion_material_file_path=['weights_1.csv','weights_2.csv','weights_3.csv','weights_4.csv','weights_5.csv','weights_6.csv']   #权重与素材映射表名字
        self.__word_material_proportion_colunms=['word_id','weights_1','weights_2','weights_3','weights_4','weights_5','weights_6']   #词库与素材权重映射的字段名字
        self.__proportion_material_colunms=['father_id','material_id','p_category']     #权重与素材映射表的字段名字
        self.__material_solidify_file_path=os.path.join(reception_base_path,'material_solidify.csv')   #素材固化表
        self.__material_solidify_colunms=['qtid','qcid','hid','atid','acid','mid','inid','eimgid','evideoid','pic']


    def __get_all_words_id(self,*args):
        '''
        根据分词与分词的比重表获取到所有的分词id
        :param args: 词汇表中过滤出来的分词的id
        :return:
        '''
        word_proportion_dataframe=pd.read_csv(self.__proportion_file_path,encoding='utf-8')
        filter_dataframe=word_proportion_dataframe[word_proportion_dataframe['word_id'].isin(args)]
        filter_proportion_1=filter_dataframe.proportion_1.values
        filter_proportion_2=filter_dataframe.proportion_2.values
        filter_proportion_3=filter_dataframe.proportion_3.values
        filter_proportion_4=filter_dataframe.proportion_4.values
        filter_proportion_5=filter_dataframe.proportion_5.values
        filter_proportion_6=filter_dataframe.proportion_6.values
        word_id_list=[]
        for sub_key in filter_proportion_6:
            word_id_list.append(str(sub_key))
        for sub_key in filter_proportion_5:
            if pd.isnull(sub_key)==False:  #判断这个字段值是否为nan
                for sub_sub in sub_key.split(';'):
                    if sub_sub not in word_id_list:
                        word_id_list.append(sub_sub)
        for sub_key in filter_proportion_4:
           if pd.isnull(sub_key)==False:  #判断这个字段值是否为nan
                for sub_sub in sub_key.split(';'):
                    if sub_sub not in word_id_list:
                        word_id_list.append(sub_sub)
        for sub_key in filter_proportion_3:
            if pd.isnull(sub_key)==False:  #判断这个字段值是否为nan
                for sub_sub in sub_key.split(';'):
                    if sub_sub not in word_id_list:
                        word_id_list.append(sub_sub)
        for sub_key in filter_proportion_2:
            if pd.isnull(sub_key)==False:  #判断这个字段值是否为nan
                for sub_sub in sub_key.split(';'):
                    if sub_sub not in word_id_list:
                        word_id_list.append(sub_sub)
        for sub_key in filter_proportion_1:
            if pd.isnull(sub_key)==False:  #判断这个字段值是否为nan
                for sub_sub in sub_key.split(';'):
                    if sub_sub not in word_id_list:
                        word_id_list.append(sub_sub)
        word_id_list=[int(i) for i in word_id_list]
        return word_id_list


    def __get_material_id(self,*args,**kwargs):
        '''
        对分词进行与素材对应，并且返回素材的信息
        :param args: 分词与分词之间的比重关系表中各个比重中的分词id集合
        :return:
        '''
        items=[]
        material_show_level={}
        flag_dict={'0':[1,2,3,4,5,6,7,8,9],'1':[1,2,3,4,5],'2':[6],'3':[7],'4':[9],'5':[8]}
        flag=kwargs['flag']

        weights_dataframe=pd.read_csv(self.__word_material_proportion_file_path,encoding='utf-8')
        filter_weights_dataframe=weights_dataframe[weights_dataframe['word_id'].isin(args)]   #根据分词过滤出来的记录
        weights_index=filter_weights_dataframe.index.values

        weights_6_dataframe=pd.read_csv(os.path.join(reception_base_path,self.__proportion_material_file_path[-1]),encoding='utf-8')    #获取100权重的素材映射表数据
        material_dataframe=weights_6_dataframe[(weights_6_dataframe['father_id'].isin(weights_index))&(weights_6_dataframe['p_category'].isin(flag_dict.get(flag,[])))]
        material_id=material_dataframe.material_id.values
        material_type=material_dataframe.p_category.values
        columns = list(weights_6_dataframe.columns)
        if 'show_level' in columns:
            show_level=material_dataframe.show_level.values
        else:
            show_level=map(lambda x:0,range(material_id.__len__()))
        for sub_key in range(material_id.__len__()):
            temp_show_level=material_show_level.get(str(int(material_id[sub_key]))+'-'+str(int(material_type[sub_key])),100)
            if temp_show_level>int(show_level[sub_key]):
                material_show_level[str(int(material_id[sub_key]))+'-'+str(int(material_type[sub_key]))]=int(show_level[sub_key])
        for key,value in material_show_level.items():
            items.append((int(key.split('-')[0]),int(key.split('-')[1]),value))
        items=sorted(items,key=lambda x:x[2])
        return items


    def __get_pic_video(self,material_list=[]):
        '''
        内部方法，获取题目图片路径 答案图片路径  考点视频路径
        :param material_list: 素材的id和类型的list type list 元素的type是元组
        :return:
        '''
        q_pic_id=[]   #题目的id
        a_pic_id=[]   #答案的id
        video_id=[]   #视频的考点id
        extend_id=[]   #额外资源的id
        exam_id=[]     #试卷id
        q_pic_items={}
        a_pic_items={}
        video_items={}
        exam_items={}
        extend_list=[]
        extend_show_level={}
        exam_list=[]

        for key,value,show_level in material_list:
            if value==2:
                q_pic_id.append(key)
            if value==5:
                a_pic_id.append(key)
            if value==6:
                video_id.append(key)
            if value==8:
                extend_id.append(key)
                temp_show_level=extend_show_level.get(key,100)
                if show_level<temp_show_level:
                    extend_show_level[key]=show_level
            if value==9:
                exam_id.append(key)

        solidify_dataframe=pd.read_csv(self.__material_solidify_file_path,encoding='utf-8')
        q_pic_dataframe=solidify_dataframe[solidify_dataframe['qcid'].isin(q_pic_id)]    #获取题目图片的记录集合
        q_pic_id_list=q_pic_dataframe.qcid.values
        q_pic_list=q_pic_dataframe.pic.values
        for sub_key in range(q_pic_id_list.__len__()):
            q_pic_items[int(q_pic_id_list[sub_key])]=q_pic_list[sub_key]




        a_pic_dataframe=solidify_dataframe[solidify_dataframe['acid'].isin(a_pic_id)]
        a_pic_id_list=a_pic_dataframe.acid.values
        a_pic_list=a_pic_dataframe.pic.values
        for sub_key in range(a_pic_id_list.__len__()):
            a_pic_items[int(a_pic_id_list[sub_key])]=a_pic_list[sub_key]


        columns=list(solidify_dataframe.columns)

        if 'extendid' in columns:
            extend_dataframe=solidify_dataframe[solidify_dataframe['extendid'].isin(extend_id)]
            extend_id_list=extend_dataframe.extendid.values
            extend_list=map(lambda x:int(x),extend_id_list)
            temp_id_list=[]
            for key,value in extend_show_level.items():
                if key in extend_list:
                    temp_id_list.append((key,value))
            temp_id_list=sorted(temp_id_list,key=lambda x:x[1])
            extend_list=map(lambda x:x[0],temp_id_list)



        if 'examid' in columns:
            exam_dataframe=solidify_dataframe[solidify_dataframe['examid'].isin(exam_id)]
            exam_id_list=exam_dataframe.examid.values
            exam_list=map(lambda x:int(x),exam_id_list)







        # video_dataframe=solidify_dataframe[solidify_dataframe['mid'].isin(video_id)]
        # video_id_list=video_dataframe.mid.values
        # video_list=video_dataframe.pic.values
        # for sub_key in range(video_id_list.__len__()):
        #     video_items[int(video_id_list[sub_key])]=video_list[sub_key]



        return q_pic_items,a_pic_items,extend_list,exam_list









    def material_handle_main(self,*args,**kwargs):
        '''
        该类的主方法
        :param args: 词汇表中过滤出来的分词的id
        :return:
        '''
        search_itmes={}
        flag=kwargs['flag']
        word_id_list=self.__get_all_words_id(*args)
        itmes=self.__get_material_id(*word_id_list,**{'flag':flag})

        #search_itmes['material']=itmes   #素材的id与素材的类型
        q_pic,a_pic,extend_list,exam_list=self.__get_pic_video(material_list=itmes)
        search_itmes['q_pic']=q_pic  #题目id与对应的图片
        search_itmes['a_pic']=a_pic  #答案id与对应的图片
        search_itmes['extend_list']=extend_list   #额外资源id
        search_itmes['exam_list']=exam_list
        #search_itmes['s_video']=s_video   #考点的id与对应的视频
        qid=[]   #题目id
        aid=[]   #答案id
        mid=[]   #视频的考点id
        mid_dict={}
        for material_id,material_type,show_level in itmes:
            if material_type in [1,2,3]:
                qid.append(int(material_id))
            if material_type in [4,5]:
                aid.append(int(material_id))
            if material_type==6:
                temp_show_level=mid_dict.get(int(material_id),100)
                if temp_show_level>show_level:
                    mid_dict[int(material_id)]=show_level
        for key,value in mid_dict.items():
            mid.append((key,value))
        mid=map(lambda x:x[0],sorted(mid,key=lambda x:x[1]))
        search_itmes['qid']=list(set(qid))
        search_itmes['aid']=list(set(aid))
        search_itmes['mid']=mid
        return search_itmes





